<template>
  <div class="home">
    <Layout>
      <!-- 头部区域 -->
      <Header v-if="state.show" class="header">
        <!-- logo -->
        <div class="logo">
          <a href="https://gitcode.com/yk123666/yike/overview">
            <img class="gitcode" :src="gitcode" alt="gitcode" />
          </a>
        </div>
        <div class="logo">壹刻绘画</div>
        <div style="float: right; position: absolute; bottom: 0px; right: 10px">
          <!-- <waterMark /> -->
          <!-- <import-JSON></import-JSON> -->
          <save></save>
        </div>
      </Header>
      <Content style="display: flex; height: calc(100vh - 64px)">
        <!-- 左侧区域 -->
        <div v-if="state.show" :class="`left-bar ${state.toolsBarShow && 'show-tools-bar'}`">
          <Menu :active-name="state.menuActive" accordion @on-select="showToolsBar" width="65px">
            <MenuItem :name="2" class="menu-item">
              <Icon
                width="19"
                height="24"
                icon="streamline:interface-dashboard-layout-3-app-application-dashboard-home-layout"
                :horizontalFlip="true"
                :verticalFlip="true"
              />
              <div>添加</div>
            </MenuItem>
            <!-- <MenuItem :name="1" class="menu-item">
              <Icon icon="majesticons:image-line" width="22" height="28" />
              <div>海报</div>
            </MenuItem> -->
            <!-- <MenuItem :name="3" class="menu-item">
              <Icon type="ios-leaf-outline" size="24" />
              <div>卡通</div>
            </MenuItem> -->
            <MenuItem :name="4" class="menu-item">
              <Icon
                icon="majesticons:list-box-line"
                width="22"
                height="28"
                :horizontalFlip="true"
                :verticalFlip="true"
              />
              <div>图层</div>
            </MenuItem>
            <div class="help">
              <div @click="help = true" type="primary">
                <Icon icon="charm:help" width="22" height="28" />
                <div>帮助</div>
              </div>
            </div>
            <Drawer title="使用说明" :closable="false" v-model="help" width="40">
              <Table :columns="columns" :data="data"></Table>
              <div class="px-4 py-2 text-lg font-bold">
                标题文本输入支持
                <a target="_blank" href="https://www.emojiall.com/zh-hans/all-emojis?type=normal">
                  emoji图标
                </a>
                !
              </div>
              <div class="flex w-full">
                <img loading="lazy" :src="me" alt="" class="h-56" />
              </div>
            </Drawer>
          </Menu>
          <Divider type="vertical" class="divider" />
          <div class="content" v-show="state.toolsBarShow">
            <!-- 生成模板 -->
            <div v-show="state.menuActive === 1" class="left-panel">
              <import-tmpl ref="importTmpls"></import-tmpl>
            </div>
            <!-- 常用元素 -->
            <div v-show="state.menuActive === 2" class="left-panel">
              <tools></tools>
              <!-- <fontTmpl></fontTmpl> -->
            </div>
            <!-- 图层设置 -->
            <div v-show="state.menuActive === 4" class="left-panel">
              <layer></layer>
            </div>
          </div>

          <!-- 关闭按钮 -->
          <div class="close-btn" v-show="state.toolsBarShow" @click="hideToolsBar"></div>
        </div>

        <!-- 画布区域 -->
        <div id="workspace">
          <div class="canvas-box">
            <div class="inside-shadow"></div>
            <canvas id="canvas" :class="stateRuler.ruler ? 'design-stage-grid' : ''"></canvas>
            <dragMode v-if="state.show"></dragMode>
            <zoom v-if="state.show"></zoom>
          </div>
        </div>

        <!-- 属性区域 380-->
        <div class="right-bar" v-show="state.attrBarShow">
          <div v-if="state.show" style="padding-top: 10px">
            <!-- 新增字体样式使用 -->
            <!-- <Button @click="getFontJson" size="small">获取字体数据</Button> -->
            <set-size />
            <bg-bar></bg-bar>
            <group></group>
            <!-- <replaceImgOld /> -->
            <replaceImg></replaceImg>
            <filters></filters>
            <div class="attr-item">
              <lock></lock>
              <dele></dele>
              <clone></clone>
            </div>
            <!-- 组对齐方式 -->
            <align></align>
            <!-- 居中对齐 -->
            <center-align></center-align>
            <!-- 翻转 -->
            <flip></flip>
          </div>
          <attribute v-if="state.show"></attribute>
        </div>
        <!-- 右侧关闭按钮 -->
        <div
          :class="`close-btn right-btn ${state.attrBarShow && 'right-btn-open'}`"
          @click="switchAttrBar"
        ></div>
      </Content>
    </Layout>
  </div>
  <Modal v-model="modal2" :mask-closable="false" @on-ok="() => canvasEditor.insertSvgFile(fileStr)">
    <p class="m-10">检测到上次编辑存在记录，是否恢复？</p>
  </Modal>
</template>

<script name="Home" setup>
import gitcode from '@/assets/gitcode-logo-dark.png';
const columns = [
    {
      title: '操作',
      key: 'key',
    },
    {
      title: '快捷键',
      key: 'value',
    },
  ],
  data = [
    {
      key: '复制',
      value: 'Ctrl + c',
    },
    {
      key: '粘贴',
      value: 'Ctrl + v',
    },
    {
      key: '撤销',
      value: 'Ctrl + z',
    },
    {
      key: '恢复',
      value: 'Ctrl + shift + z',
    },
    {
      key: '删除',
      value: 'Delete / Backspace',
    },
    {
      key: '-----',
      value: '---------',
    },
    {
      key: '多选',
      value: '长按Shift + 鼠标左键',
    },
    {
      key: '缩放画布',
      value: '鼠标滚轮',
    },
    {
      key: '移动画布',
      value: 'Space(空格) + 鼠标拖拽',
    },
    {
      key: '图层设置',
      value: '鼠标右键',
    },
  ];

import { Icon } from '@iconify/vue';
// 导入元素
// import importJSON from '@/components/importJSON.vue';
import template from '@/assets/data/template';
// import fontTmpl from '@/components/fontTmpl.vue';

// 顶部组件
import align from '@/components/align.vue';
import centerAlign from '@/components/centerAlign.vue';
import flip from '@/components/flip.vue';
import save from '@/components/save.vue';
import clone from '@/components/clone.vue';
import group from '@/components/group.vue';
import zoom from '@/components/zoom.vue';
import dragMode from '@/components/dragMode.vue';
import lock from '@/components/lock.vue';
import dele from '@/components/del.vue';
// import waterMark from '@/components/waterMark';

// 左侧组件
import importTmpl from '@/components/importTmpl.vue';
import tools from '@/components/tools.vue';
import bgBar from '@/components/bgBar.vue';
import setSize from '@/components/setSize.vue';
import replaceImg from '@/components/replaceImg.vue';
// import replaceImgOld from '@/components/replaceImgOld.vue';
import filters from '@/components/filters.vue';

// 右侧组件
import layer from '@/components/layer.vue';
import attribute from '@/components/attribute.vue';

// 功能组件
import { CanvasEventEmitter } from '@/utils/event/notifier';
// import { downFile } from '@/utils/utils';
import { fabric } from 'fabric';
import Editor, {
  DringPlugin,
  AlignGuidLinePlugin,
  ControlsPlugin,
  ControlsRotatePlugin,
  CenterAlignPlugin,
  LayerPlugin,
  CopyPlugin,
  MoveHotKeyPlugin,
  DeleteHotKeyPlugin,
  GroupPlugin,
  DrawLinePlugin,
  GroupTextEditorPlugin,
  GroupAlignPlugin,
  WorkspacePlugin,
  DownFontPlugin,
  HistoryPlugin,
  FlipPlugin,
  RulerPlugin,
  MaterialPlugin,
} from '@/core';
import { useRoute } from 'vue-router';

import { storeToRefs } from 'pinia';
import { reactive, ref } from 'vue';
import editorStore from '@/store/editor';
const editorStorer = editorStore();
let { state: stateRuler } = storeToRefs(editorStorer);

// 创建编辑器
const canvasEditor = new Editor();

const event = new CanvasEventEmitter();

const state = reactive({
  menuActive: 2,
  show: false,
  toolsBarShow: true,
  attrBarShow: true,
  select: null,
  ruler: true,
});

function transformText(objects) {
  if (!objects) return;
  objects.forEach((item) => {
    if (item.objects) {
      transformText(item.objects);
    } else {
      item.type === 'text' && (item.type = 'textbox');
    }
  });
}

const help = ref(false);
const importTmpls = ref(null);
let modal2 = ref(false);
let fileStr = ref(false);
onMounted(() => {
  // 初始化fabric
  const canvas = new fabric.Canvas('canvas', {
    selectionFullyContained: true, // 精准选择
    fireRightClick: true, // 启用右键，button的数字为3
    stopContextMenu: true, // 禁止默认右键菜单
    controlsAboveOverlay: true, // 超出clipPath后仍然展示控制条
  });

  // 初始化编辑器
  canvasEditor.init(canvas);
  canvasEditor.use(DringPlugin);
  canvasEditor.use(AlignGuidLinePlugin);
  canvasEditor.use(ControlsPlugin);
  canvasEditor.use(ControlsRotatePlugin);
  canvasEditor.use(CenterAlignPlugin);
  canvasEditor.use(LayerPlugin);
  canvasEditor.use(CopyPlugin);
  canvasEditor.use(MoveHotKeyPlugin);
  canvasEditor.use(DeleteHotKeyPlugin);
  canvasEditor.use(GroupPlugin);
  canvasEditor.use(DrawLinePlugin);
  canvasEditor.use(GroupTextEditorPlugin);
  canvasEditor.use(GroupAlignPlugin);
  canvasEditor.use(WorkspacePlugin);
  canvasEditor.use(DownFontPlugin);
  canvasEditor.use(HistoryPlugin);
  canvasEditor.use(FlipPlugin);
  canvasEditor.use(RulerPlugin);
  canvasEditor.use(MaterialPlugin);

  event.init(canvas);
  state.show = true;

  // 解析url参数，跳转指定模板/设置指定宽高/打开上次记录;
  const Route = useRoute();
  const target = Route.query?.id?.split('-');
  const width = Number(Route.query?.w?.split('-'));
  const height = Number(Route.query?.h?.split('-'));

  setTimeout(() => {
    if (target) {
      importTmpls.value.getTempData(template.data[target[0] - 1].list[target[1] - 1].tempUrl);
    } else if (width && height) {
      canvasEditor.setSize(width, height);
      editorStorer.setData({ width, height });
    } else {
      fileStr.value = localStorage.getItem('canvasEditor');
      fileStr.value.length > 1600 ? (modal2.value = true) : '';
    }
    window.history.pushState('', '', window.location.origin + window.location.pathname + '#/');
  }, 0);

  window.onbeforeunload = function () {
    // 页面关闭前保存当前编辑状态
    const dataUrl = canvas.toJSON(['id', 'gradientAngle', 'selectable', 'hasControls']);
    transformText(dataUrl.objects);
    const fileStr = JSON.stringify(dataUrl, null, '\t');
    localStorage.setItem('canvasEditor', fileStr);
    // return '你所做的更改可能未保存。';
  };
});

// 获取字体数据 新增字体样式使用
// getFontJson() {
//   const activeObject = this.canvas.getActiveObject();
//   if (activeObject) {
//     const json = activeObject.toJSON(['id', 'gradientAngle', 'selectable', 'hasControls']);
//     console.log(json);
//     const fileStr = `data:text/json;charset=utf-8,${encodeURIComponent(
//       JSON.stringify(json, null, '\t')
//     )}`;
//     downFile(fileStr, 'font.json');
//     const dataUrl = activeObject.toDataURL();
//     downFile(dataUrl, 'font.png');
//   }
// },

// 隐藏工具条
const hideToolsBar = () => {
  state.menuActive = 100;
  state.toolsBarShow = false;
};
// 展示工具条
const showToolsBar = (val) => {
  state.menuActive = val;
  state.toolsBarShow = true;
};
// 属性面板开关
const switchAttrBar = () => {
  state.attrBarShow = !state.attrBarShow;
};

provide('fabric', fabric);
provide('event', event);
provide('canvasEditor', canvasEditor);
</script>
<style lang="less" scoped>
.help {
  position: absolute;
  bottom: 1em;
  width: 100%;
  text-align: center;
}
.header {
  height: 48px !important;
}
.divider {
  height: 100vh !important;
}
:deep(.ivu-layout) {
  background-color: #ffffff !important;
}

:deep(.ivu-layout-header) {
  background-color: #ffffff;
  border-bottom: 1px solid #ccc;
}
:deep(.ivu-menu::after) {
  display: none;
}
:deep(.ivu-menu-item-active::after) {
  display: none !important;
}
:deep(.ivu-menu-item-selected) {
  color: #222222 !important;
  background: #eff2f7 !important;
  border-radius: 15px;
}
:deep(.ivu-menu-item:hover) {
  color: #222222 !important;
  background-color: #f7f8fa !important;
  border-radius: 15px;
}

.logo {
  display: inline-block;
  margin-left: 10px;
  font-size: 24px;
  vertical-align: middle;
}

.gitcode {
  display: inline-block;
  vertical-align: middle;
  width: 120px;
}

// 左侧容器
.left-bar {
  width: 65px;
  height: 100%;
  background: #fff;
  display: flex;
  position: relative;

  &.show-tools-bar {
    width: 390px;
  }
}
// 右侧容器
.right-bar {
  width: 304px;
  height: 100%;
  padding: 10px;
  overflow-y: auto;
  background: #fff;
}

// 关闭按钮
.close-btn {
  width: 20px;
  height: 64px;
  cursor: pointer;
  background-image: url();
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
  position: absolute;
  right: -20px;
  z-index: 1;
  top: 50%;
  margin-top: -10px;

  &.right-btn {
    background-image: url();
    transform: rotateY(180deg);
    right: 0px;
  }

  &.right-btn-open {
    background-image: url();
    right: 304px;
  }
}

// 属性面板样式
:deep(.attr-item) {
  position: relative;
  margin-bottom: 12px;
  height: 40px;
  padding: 0 10px;
  background: #f6f7f9;
  border: none;
  border-radius: 4px;
  display: flex;
  align-items: center;
  .ivu-tooltip {
    text-align: center;
    flex: 1;
  }
}

.ivu-menu-vertical .menu-item {
  width: 54px;
  text-align: center;
  padding: 10px 2px;
  box-sizing: border-box;
  font-size: 12px;
  margin-top: 10px;
  margin-left: 8px;
  & > i {
    margin: 0;
  }
}

:deep(.ivu-layout-header) {
  position: relative;
  --height: 45px;
  padding: 0 10px;
  border-bottom: 1px solid #eef2f8;
  background: #fff;
  height: var(--height);
  line-height: var(--height);
}

.home,
.ivu-layout {
  height: 100vh;
  overflow: hidden;
}

.icon {
  display: block;
}

.canvas-box {
  position: relative;
}
// 画布内阴影
.inside-shadow {
  position: absolute;
  width: 100%;
  height: 100%;
  box-shadow: inset 0 0 9px 2px #0000001f;
  z-index: 2;
  pointer-events: none;
}

#canvas {
  width: 300px;
  height: 300px;
  margin: 0 auto;
}

#workspace {
  flex: 1;
  width: 100%;
  position: relative;
  background: #f1f1f1;
  overflow: hidden;
}

.content {
  flex: 1;
  width: 256px;
  padding: 7px;
  padding-top: 0;
  height: 100%;
  overflow-y: auto;
}

.ivu-menu-light.ivu-menu-vertical .ivu-menu-item-active:not(.ivu-menu-submenu) {
  background: none;
}
// 标尺
.switch {
  margin-right: 10px;
}
// 网格背景
.design-stage-grid {
  --offsetX: 0px;
  --offsetY: 0px;
  --size: 16px;
  --color: #dedcdc;
  background-image: linear-gradient(
      45deg,
      var(--color) 25%,
      transparent 0,
      transparent 75%,
      var(--color) 0
    ),
    linear-gradient(45deg, var(--color) 25%, transparent 0, transparent 75%, var(--color) 0);
  background-position: var(--offsetX) var(--offsetY),
    calc(var(--size) + var(--offsetX)) calc(var(--size) + var(--offsetY));
  background-size: calc(var(--size) * 2) calc(var(--size) * 2);
}
</style>
